/*
 * @Descripttion: 优化性质函数 防抖、节流
 * @version:
 * @Author: lhl
 * @Date: 2024-09-04 14:38:15
 * @LastEditors: lhl
 * @LastEditTime: 2024-09-04 14:42:07
 */

/**
 * 节流函数
 * @param func 需要节流的函数
 * @param wait 等待时间，单位为毫秒 默认 500 毫秒
 * @returns 节流后的函数
 */
export const throttle = <T extends (...args: any[]) => any>(func: T, wait: number = 500): T => {
  // ReturnType<typeof setTimeout>：获取 setTimeout 函数的返回值类型，并将其赋值给 timeout 变量
  let timeout: ReturnType<typeof setTimeout> | null = null;
  // 获取函数 T 的参数类型，并将其赋值给 lastArgs 变量
  let lastArgs: Parameters<T> | null = null;

  const throttled = function (...args: Parameters<T>) {
    lastArgs = args;

    if (!timeout) {
      timeout = setTimeout(() => {
        if (lastArgs) {
          func(...lastArgs);
          lastArgs = null;
          timeout = null;
        }
      }, wait);
    }
  };

  return throttled as T;
};

/**
 * 防抖函数
 * @param func 需要防抖的函数
 * @param wait 等待时间，单位为毫秒 默认 500 毫秒
 * @returns 防抖后的函数
 */
export const debounce = <T extends (...args: any[]) => any>(func: T, wait: number = 500): T => {
  let timeout: ReturnType<typeof setTimeout> | null = null;

  const debounced = function (this: any, ...args: Parameters<T>) {
    if (timeout) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(() => {
      func.apply(this, args);
      timeout = null;
    }, wait);
  };

  return debounced as T;
};
